package br.com.rafsoft.mapaentrega.activity.async;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import br.com.rafsoft.mapaentrega.MapaEntregaApplication;
import br.com.rafsoft.mapaentrega.Util;
import br.com.rafsoft.mapaentrega.activity.MessageListActivity;
import br.com.rafsoft.mapaentrega.shared.MapaEntregaRequestFactory;
import br.com.rafsoft.mapaentrega.shared.MessageProxy;

import com.google.web.bindery.requestfactory.shared.Receiver;

public class AsyncFetchMessage extends AsyncTask<Long, Void, List<MessageProxy>> {

	private final MessageListActivity activity;
	private boolean newMessage = false;

	public AsyncFetchMessage(MessageListActivity activity) {
		super();
		this.activity = activity;
	}

	@Override
	protected List<MessageProxy> doInBackground(Long... arguments) {
		final List<MessageProxy> list = new ArrayList<MessageProxy>();

		// INSERT RPC HERE!
		MapaEntregaRequestFactory factory = Util.getRequestFactory(activity,
				MapaEntregaRequestFactory.class);

		if (arguments.length == 0 || arguments[0] == -1) {
			MapaEntregaApplication application = (MapaEntregaApplication) activity.getApplication();
			factory.messageRequest().queryMessagesUser(application.getUser())
					.fire(new Receiver<List<MessageProxy>>() {
						@Override
						public void onSuccess(List<MessageProxy> arg0) {
							list.addAll(arg0);
							//activity.setMessages(arg0);
						}
					});
		} else {
			newMessage = true;
			factory.messageRequest().readMessage(arguments[0])
					.fire(new Receiver<MessageProxy>() {

						@Override
						public void onSuccess(MessageProxy arg0) {
							list.add(arg0);
						}
					});
		}

		return list;
	}

	@Override
	protected void onPostExecute(List<MessageProxy> result) {
		if (newMessage) {
			activity.addMessages(result);
		} else {
			activity.setMessages(result);
		}
	}
}
